{include file="admin@public/header" /}

<link rel="stylesheet" href="/public/static/admin/easyui/layui-v2.6.8/css/layui.css">
<!-- <link rel="stylesheet" type="text/css" href="/public/static/admin/easyui/jeasyui/themes/icon.css"> -->

<link href="/public/static/admin/blue/bills.css" rel="stylesheet" type="text/css">

<style>
  /*#barCodeInsert{margin-left: 10px;font-weight: 100;font-size: 12px;color: #fff;background-color: #B1B1B1;padding: 0 5px;border-radius: 2px;line-height: 19px;height: 20px;display: inline-block;}*/
  /*#barCodeInsert.active{background-color: #23B317;}*/
  .url-box {
    padding: 5px 10px;
    line-height: 20px;
    cursor: pointer;
  }

  .url-box a {
    margin-right: 5px;
  }

  .con-header dd #editBills {
    background: url(/public/static/admin/css/img/edit.png);
    display: inline-block;
    width: 13px;
    height: 12px;
  }

  #check_history {
    background: green;
    border-radius: 10px 10px;
    width: 80px;
    text-align: center;
  }

  #check_history a {
    color: #fff;
  }

  .wrapper_con {
    overflow-y: auto;
    overflow-x: hidden;
  }

  .ui-jqgrid a.srcOrderNo {
    text-decoration: none;
    cursor: pointer;
  }

  .ui-jqgrid a.srcOrderNo:hover {
    text-decoration: none;
  }

  .layui-form-radio {
    margin-top: 0;
  }

  .layui-form-radio>i:hover,
  .layui-form-radioed>i {
    color: #3CBAFF;
  }

  .pcnone {
    display: none !important;
  }
</style>

<div class="wrapper">
  <div class="mod-toolbar-top mr0 cf dn" id="toolTop"></div>
  <div class="bills cf ">
    <div class="con-header layui-form">
      <dl class="cf">
        <dd class="mr20">
          <label><span class="red">*</span>供应商:</label>
          <span class="ui-combo-wrap" id="customer" onclick="chooseSupplier(1,0)" style="width: 198px;">

            <i class="ui-icon-ellipsis"></i><input type="text" name="" class="input-txt" autocomplete="off" value=""
              data-ref="date" style="width: 188px;"></span>
          <input type="hidden" id="customerid" value="" autocomplete="off" readonly="">
        </dd>
        <dd class="mr20">
          <label>单据日期:</label>
          <input type="date" id="dj_time" class="ui-input " value="{$today}" style="width: 125px;">
        </dd>
        {include file="admin@public/order/change_sn" /}
      </dl>
      <hr class="hrcls">
    </div>

    <div class="wrapper_con">
      <!-- <div class="cf mb10">
		  <div class="fl">
			<span  id="config" class="ui-config"><a href="#" class="ui-icon-config-new"></a>列设置</span>
			<span><label>扫描枪录入</label><span id="barCodeInsert" class="close"><span class="ui-icon-circle"></span></span></span>
		  </div>
		  <div class="fr">
			<span class="circle-link-order linkToCheck"><a href="#" class="icon-link-order"></a>历史单据</span>
		  </div>
		</div> -->
      <span id="config" class="ui-config"><a href="#" class="ui-icon-config-new"></a></span>
      <div class="grid-wrap">
        <table id="grid"></table>
        <div id="page"></div>
      </div>
      <div class="cf" id="bottomField">
        <span id="groupBtn">
          <a id="savaAndAdd" class="ui-btn ui-btn-sp">保存并新增</a>
          <a id="save" class="ui-btn">保存</a>
          <a class="ui-btn" id="o_shenhe">审核</a>
        </span>
      </div>
      <div id="mark"></div>
    </div>

    <div class="con-footer cf">
      <div class="mb10">
        <textarea type="text" id="note" class="ui-input ui-input-ph" placeholder="暂无备注信息"></textarea>
      </div>
    
       {include file="admin@public/yh" /}
      <ul  class="cf">
         {include file="admin@public/order/payment" /}
      </ul>

      <div class="cf fr">
        <a class="linkToCheck ui-btn-bill ui-btn-add mr20"  onclick="addPage('/scm/invre/index.html','purchaseRe','购货退货单记录')" ><span></span>历史单据</a>
        <a href="#" id="operaLog" class="ui-btn">操作日志</a>
      </div>
    </div>

    <!-- 操作日志 -->
		<ul id="operaLogBox" class="shadow opera-log-box " style="position: absolute;z-index: 999; display: none;">
			<li>
			  <span class="fl" style="margin-right: 50px;"><label>制单人：</label><span id="userName"
				  style="margin-left: 12px;"><span open-data="" title="{$admin.name}">{$admin.name}</span></span></span>
			</li>
			<!-- <li>
			  <span class="fl"><label>制单时间：</label><span id="createTime"></span></span>
			</li>
			<li>
			  <span class="fl"><label>审核人：</label><span id="checkName" style="margin-left: 12px;"></span></span>
			</li>
			<li>
			  <span class="fl"><label>审核时间：</label><span id="checkTime"></span></span>
			</li>
			<li>
			  <span class="fl"><label>最后修改人：</label><span id="modifyName" style="margin-left: 12px;"></span></span>
			</li>
			<li>
			  <span class="fl"><label>最后修改时间：</label><span id="modifyTime"></span></span>
			</li> -->
		</ul>


    <div id="initCombo" class="dn">
      <input type="text" class="textbox goodsAuto" name="goods" autocomplete="off">
      <input type="text" class="textbox storageAuto" name="storage" autocomplete="off">
      <input type="text" class="textbox unitAuto" name="unit" autocomplete="off">
      <input type="text" class="textbox priceAuto" name="price" autocomplete="off">
      <input type="text" class="textbox skuAuto" name="price" autocomplete="off">
    </div>

    <div id="discountRateBox" class="shadow target_box dn"></div>
    <div id="goodsDiscountRateBox" class="shadow target_box dn"></div>
    <div id="deductionBox" class="shadow target_box dn"></div>
    <div id="snapshotTipsBox" class="shadow target_box dn"></div>




   {include file="admin@public/order/choose_good" /}
    <!-- 仓库弹窗 -->
  {include file="admin@public/order/choose_store" /}

</div>


<script type="text/javascript">
  $(document).ready(function () {
   

    // 操作日志鼠标移入移除
    $("#operaLog").hover(function () {
      var top = $(this).offset().top;
      // var left = $(this).offset().left;
      $("#operaLogBox").show();
      $("#operaLogBox").css({ "right": "30px", "top": (top + 20) + "px" })
    }, function () {
      $("#operaLogBox").hide();
    })
    

   
  });
  
</script>

<script type="text/javascript">
  var Pdata;
  var edit_row = 0;
  var edit_col = 0;
  var row_id = 0;
  var col_name = 0;

  $(document).ready(function () {
    // 跳转打开新标签页
    $(".ta").click(function () {
      var tabid = $(this).attr('tabid');
      var tabTxt = $(this).attr('tabTxt');
      var _href = $(this).attr('_href');
      parent.tab.addTabItem({
        tabid: tabid,
        text: tabTxt,
        url: _href
      })
    });

    localStorage.clear(); //清空local

    // 采购费用
    $("#expenseInfo").on("click", function () {
      expenseInfoFun('/scm/invpu/purchase_cost.html', this);
    });



    var outhtml = '';
    var inhtml = ' ';
    var goods = '<span class="red">*</span>商品<label> -- 扫描枪录入</label><span id="barCodeInsert" class="open" onclick="smq();"><span class="ui-icon-circle"></span></span>';
    var batch = '<span class="red">*</span>仓库<small id="batchStorage1" onclick="batchBtn(1);" class="btns">批量</small>';
    var inventory = '可用库存<img src="/public/static/admin/css/img/help.png" style="width: 20px;display: inline-block;margin-left: 5px;" onclick="snapshotTipsFun()" id="snapshotTipsBtn"/>';
    var zk_lv = '折扣率(%)<small id="batchStorage2" onclick="batchBtn(2);" class="btns">批量</small>';
    var zk_e = '折扣额<small id="batchStorage3" onclick="batchBtn(3);" class="btns">批量</small>';


    $("#grid").jqGrid({
      // url: '/admin/store/index.html?ajax=100',
      datatype: "local",//数据来源，本地数据（local，json,jsonp,xml等）
      height: '90%',//高度，表格高度。可为数值、百分比或'auto'
      colNames: ['操作', '', goods, '商品备注', '单位', batch, inventory, '<span class="red">*</span>数量', '基本单位', '基本数量', '购货单价', '含税单价', zk_lv, zk_e, '金额', '税率(%)', '税额', '价税合计', '采购费用', '备注', '关联销货订单号', '商品ID', '仓库id', '单位id','基本单位'],
      colModel: [
        { name: '', width: 70, formatter: cLink ,align:'center' },
        { name: 'id', index: 'id', width: 40 ,hidden:true},
        {
          name: "good_name",
          label: "商品",
          width: 300,
          title: !0,

          classes: "goods",
          editable: true,
          edittype: "custom",
          editoptions: {
            custom_element: function (t, e) {
              $("#pelem_goods").html('<div class="pr" id="elem_goods"><input type="text" class="textbox  customelement" name="good_name" autocomplete="off" ><span class="ui-icon-ellipsis"></span></div>');
              return $("#elem_goods");
            },
            custom_value: function (t, e, a) {
              var ad = $("#good_name").val();
              $("#good_name").val("");//重置赋值
              return ad;
            },
            handle: function () {

            },
            trigger: "ui-icon-ellipsis"
          }
        },
        { name: 'good_mark', width: 100, label: "商品备注" },
        { name: 'unit_name', index: '', width: 100, label: "单位" },
        {
          name: "store_name",
          label: '<span class="red">*</span>仓库',
          nameExt: '<small id="batchStorage">批量</small>',
          width: 100,
          link: "inventory",
          editable: !0,
          edittype: "custom",
          editoptions: {
            custom_element: function (t, e) {
             
                $("#p_store_name_details").html('<div class="pr" id="store_name_details"><input value="'+t+'" type="text" class="textbox storageAuto customelement ui-combo-active" name="store_name" autocomplete="off" style="outline: -webkit-focus-ring-color auto 5px;"><span class="ui-icon-triangle-1-s store_name_details"></span></div>');
                return $("#store_name_details");
            },
            custom_value: function (t, e, a) {
              var ba = $("#store_name").val();
              $("#store_name").val("");//重置赋值
              return ba;
            },
            trigger: "ui-icon-triangle-1-s"
          }
        },
        { name: 'use_kc', index: '', width: 80, label: "可用库存", },
        { name: 'shuliang', index: '', width: 80, label: "数量", editable: true },
        { name: 'base_unit_name', index: '', width: 100, label: "基本单位", editable: false },
        { name: 'base_number', index: '', width: 100, label: "基本数量", editable: false },
        { name: 'price', index: '', width: 100, label: "购货单价", editable: true },
        { name: 'hs_price', index: '', width: 100, label: "含税单价", editable: true },
        { name: 'zk_lv', index: '', width: 126, label: "折扣率(%)", editable: true },
        { name: 'zk_e', index: '', width: 126, label: "折扣额", editable: true },
        { name: 'jine', index: '', width: 100, label: "金额", editable: true },
        { name: 'tax_lv', index: '', width: 100, label: "税率", editable: true },
        { name: 'tax_e', index: '', width: 100, label: "税额", editable: true },
        { name: 'total_price', index: '', width: 100, label: "价税合计", editable: true },
        { name: 'purchase_cost', index: '', width: 100, label: "采购费用", editable: true },
        { name: 'mark', index: '', width: 150, label: "备注", editable: true },
        { name: 'srcOrderNo', index: '', width: 150, label: "关联销货订单号", editable: false },
        { name: 'good_id', width: 100, hidden: true },
        { name: 'store_id', width: 100, hidden: true },
        { name: 'unit_id', width: 100, hidden: true },
        { name: 'base_unit_id', width: 100, hidden: true },
      ],
      cellEdit: true,
      cellurl: '/',
      rowNum: 10,
      rowList: [10, 20, 30],
      sortname: 'id',
      sortorder: "desc",
      pagerpos: "left",//分页位置
      rownumbers:true,
      pgbuttons: true,//翻页按钮
      pagination: true,
      altRows: !0,
      gridview: !0,
      shrinkToFit: !1,
      cellLayout: 8,
      autowidth: !0,
      pager: "#page",
      viewrecords: !0,
      cmTemplate: {
        sortable: !1,
        title: !1
      },
      // 合计
      footerrow: true,
      gridComplete: function () {
        var shuliangs = $("#grid").getCol('shuliang', false, 'sum');
        var base_numbers = $("#grid").getCol('base_number', false, 'sum');
        var zk_es = $("#grid").getCol('zk_e', false, 'sum');
        var jines = $("#grid").getCol('jine', false, 'sum');
        var tax_es = $("#grid").getCol('tax_e', false, 'sum');
        var total_prices = $("#grid").getCol('total_price', false, 'sum');
        var purchase_costs = $("#grid").getCol('purchase_cost', false, 'sum')
        $("#grid").footerData('set', { "goodsname": '合计', shuliang: shuliangs, base_number: base_numbers, zk_e: zk_es, jine: jines, tax_e: tax_es, total_price: total_prices, purchase_cost: purchase_costs });
      },
      loadError: function (t, e, i) {
        parent.Public.tips({
          type: 1,
          content: "操作失败了哦，请检查您的网络链接！"
        })
      },
      beforeEditCell: function (rowid, cellname, value, iRow, iCol) {
        col_name = cellname;
        edit_row = iRow;
        edit_col = iCol;
        row_id = rowid;
        var gname = $("#grid").jqGrid("getCell", row_id, 'goodsname');
        $("#goodsname").val(gname);



        // var ck1name=$("#grid").jqGrid("getCell",row_id,'ck1');
        // $("#ck1name").val(ck1name);
        // var ck2name=$("#grid").jqGrid("getCell",row_id,'ck2');
        // $("#ck2name").val(ck2name);

      },
      // afterEditCell: function (rowid, cellname, value, iRow, iCol) {
      //   alert("编辑后");
      //   var shuliangs = $("#grid").getCol('shuliang', false, 'sum');
      //   $("#grid").footerData('set', { "goodsname": '合计', shuliang: shuliangs});
      // },

      beforeSaveCell: function (rowid, cellname, value, iRow, iCol) {
        edit_row = iRow;
        edit_col = iCol;
        row_id = rowid;

        // 重算
        // step1 (取值)
        var shuliang = parseFloat($("#grid").jqGrid("getCell", row_id, 'shuliang'));
        var price = parseFloat($("#grid").jqGrid("getCell", row_id, 'price'));
        var hs_price = parseFloat($("#grid").jqGrid("getCell", row_id, 'hs_price'));
        var zk_lv = parseFloat($("#grid").jqGrid("getCell", row_id, 'zk_lv'));
        var zk_e = parseFloat($("#grid").jqGrid("getCell", row_id, 'zk_e'));
        var jine = parseFloat($("#grid").jqGrid("getCell", row_id, 'jine'));
        var tax_lv = parseFloat($("#grid").jqGrid("getCell", row_id, 'tax_lv'));
        var tax_e = parseFloat($("#grid").jqGrid("getCell", row_id, 'tax_e'));
        var total_price = parseFloat($("#grid").jqGrid("getCell", row_id, 'total_price'));


        // 合计的变量
        var shuliangs = $("#grid").getCol('shuliang', false, 'sum');
        var zk_es = $("#grid").getCol('zk_e', false, 'sum');
        var jines = $("#grid").getCol('jine', false, 'sum');
        var tax_es = $("#grid").getCol('tax_e', false, 'sum');
        var total_prices = $("#grid").getCol('total_price', false, 'sum');
        var purchase_costs = $("#grid").getCol('purchase_cost', false, 'sum');


        // step2 (计算)
        if (cellname == 'shuliang') {
          $("#grid").jqGrid("setCell", row_id, 'base_number', value);
          zk_e = parseFloat(price / 1 * (zk_lv / 100)).toFixed(2) * value;
          jine = parseFloat(price * value - zk_e / 1).toFixed(2);
          tax_e = parseFloat(jine / 1 * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }
        if (cellname == 'price') {
          hs_price = parseFloat(price * (1 + (tax_lv / 100))).toFixed(2);
          zk_e = parseFloat(price * (zk_lv / 100)).toFixed(2) * shuliang;
          jine = parseFloat(price * shuliang - zk_e).toFixed(2);
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'hs_price') {
          price = parseFloat(hs_price / (1 + (tax_lv / 100))).toFixed(2);
          zk_e = parseFloat(price / 1 * (zk_lv / 100)).toFixed(2) * shuliang;
          jine = parseFloat(price * shuliang - zk_e).toFixed(2);
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'zk_lv') {
          zk_e = parseFloat(price / 1 * (zk_lv / 100)).toFixed(2) * shuliang;
          jine = parseFloat(price * shuliang - zk_e).toFixed(2);
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'zk_e') {
          zk_lv = parseFloat(zk_e / 1 / shuliang / price / 1).toFixed(6) * 100;
          jine = parseFloat(price * shuliang - zk_e / 1).toFixed(2);
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'jine') {
          price = parseFloat((jine / 1) / (1 - (zk_lv / 100))).toFixed(2) / shuliang;
          hs_price = parseFloat(price / 1 * (1 + (tax_lv / 100))).toFixed(2);
          zk_e = parseFloat(price / 1 * (zk_lv / 100)).toFixed(2) * shuliang;
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'tax_lv') {
          hs_price = parseFloat(price / 1 * (1 + (tax_lv / 100))).toFixed(2);
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'tax_e') {
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        if (cellname == 'total_price') {
          jine = parseFloat(total_price / (1 + (tax_lv / 100))).toFixed(2);
          price = parseFloat(jine / (1 - (zk_lv / 100))).toFixed(2) / shuliang;
          hs_price = parseFloat(price / 1 * (1 + (tax_lv / 100))).toFixed(2);
          zk_e = parseFloat(price / 1 * (zk_lv / 100)).toFixed(2) * shuliang;
          tax_e = parseFloat(jine * (tax_lv / 100)).toFixed(2);
          total_price = parseFloat(jine / 1 + tax_e / 1).toFixed(2);
        }

        // step3 (赋值)
        $("#grid").jqGrid("setCell", row_id, 'shuliang', shuliang);
        $("#grid").jqGrid("setCell", row_id, 'price', price);
        $("#grid").jqGrid("setCell", row_id, 'hs_price', hs_price);
        $("#grid").jqGrid("setCell", row_id, 'zk_lv', zk_lv);
        $("#grid").jqGrid("setCell", row_id, 'zk_e', parseFloat(zk_e).toFixed(2));
        $("#grid").jqGrid("setCell", row_id, 'jine', jine);
        $("#grid").jqGrid("setCell", row_id, 'tax_lv', tax_lv);
        $("#grid").jqGrid("setCell", row_id, 'tax_e', tax_e);
        $("#grid").jqGrid("setCell", row_id, 'total_price', total_price);

        // 计算合计
        if (cellname == 'shuliang') {

          zk_es = parseFloat($("#grid").getCol('zk_e', false, 'sum')).toFixed(2);
          jines = parseFloat($("#grid").getCol('jine', false, 'sum')).toFixed(2);
          tax_es = parseFloat($("#grid").getCol('tax_e', false, 'sum')).toFixed(2);
          total_prices = parseFloat($("#grid").getCol('total_price', false, 'sum')).toFixed(2);
          purchase_costs = parseFloat($("#grid").getCol('purchase_cost', false, 'sum')).toFixed(2);

        }else if (cellname == 'zk_e') {

          shuliangs = $("#grid").getCol('shuliang', false, 'sum');
          jines = parseFloat($("#grid").getCol('jine', false, 'sum')).toFixed(2);
          tax_es = parseFloat($("#grid").getCol('tax_e', false, 'sum')).toFixed(2);
          total_prices = parseFloat($("#grid").getCol('total_price', false, 'sum')).toFixed(2);
          purchase_costs = parseFloat($("#grid").getCol('purchase_cost', false, 'sum')).toFixed(2);

        }else if (cellname == 'jine') {

          shuliangs = $("#grid").getCol('shuliang', false, 'sum');
          zk_es = parseFloat($("#grid").getCol('zk_e', false, 'sum')).toFixed(2);
          tax_es = parseFloat($("#grid").getCol('tax_e', false, 'sum')).toFixed(2);
          total_prices = parseFloat($("#grid").getCol('total_price', false, 'sum')).toFixed(2);
          purchase_costs = parseFloat($("#grid").getCol('purchase_cost', false, 'sum')).toFixed(2);

        }else if (cellname == 'tax_e') {

          shuliangs = $("#grid").getCol('shuliang', false, 'sum');
          zk_es = parseFloat($("#grid").getCol('zk_e', false, 'sum')).toFixed(2);
          jines = parseFloat($("#grid").getCol('jine', false, 'sum')).toFixed(2);
          total_prices = parseFloat($("#grid").getCol('total_price', false, 'sum')).toFixed(2);
          purchase_costs = parseFloat($("#grid").getCol('purchase_cost', false, 'sum')).toFixed(2);

        }else if (cellname == 'total_price') {

          shuliangs = $("#grid").getCol('shuliang', false, 'sum');
          zk_es = parseFloat($("#grid").getCol('zk_e', false, 'sum')).toFixed(2);
          jines = parseFloat($("#grid").getCol('jine', false, 'sum')).toFixed(2);
          tax_es = parseFloat($("#grid").getCol('tax_e', false, 'sum')).toFixed(2);
          purchase_costs = parseFloat($("#grid").getCol('purchase_cost', false, 'sum')).toFixed(2);

        }else if(cellname == 'purchase_cost'){

          shuliangs = $("#grid").getCol('shuliang', false, 'sum');
          zk_es = parseFloat($("#grid").getCol('zk_e', false, 'sum')).toFixed(2);
          jines = parseFloat($("#grid").getCol('jine', false, 'sum')).toFixed(2);
          tax_es = parseFloat($("#grid").getCol('tax_e', false, 'sum')).toFixed(2);
          total_prices = parseFloat($("#grid").getCol('total_price', false, 'sum')).toFixed(2);

        }else{

          shuliangs = $("#grid").getCol('shuliang', false, 'sum');
          zk_es = parseFloat($("#grid").getCol('zk_e', false, 'sum')).toFixed(2);
          jines = parseFloat($("#grid").getCol('jine', false, 'sum')).toFixed(2);
          tax_es = parseFloat($("#grid").getCol('tax_e', false, 'sum')).toFixed(2);
          total_prices = parseFloat($("#grid").getCol('total_price', false, 'sum')).toFixed(2);
          purchase_costs = parseFloat($("#grid").getCol('purchase_cost', false, 'sum')).toFixed(2);

        }

        var base_numbers = $("#grid").getCol('base_number', false, 'sum');
        $("#grid").footerData('set', { "goodsname": '合计', shuliang: shuliangs, base_number: base_numbers, zk_e: zk_es, jine: jines, tax_e: tax_es, total_price: total_prices, purchase_cost: purchase_costs });


         // 底部统计
        $('#yh_price').val(total_prices);
        $("#before_yh_price").val(total_prices);
        $('#payment').val(total_prices);
        onchange_payment();
      },
    });
    //增加、删除按钮
    function cLink(cellvalue, options, rowObject) {
      return '<div class="operating"><span class="ui-icon ui-icon-plus" title="新增行" onclick="add_row(' + options.rowId + ')" style="margin:0 2px;"></span> <span class="ui-icon ui-icon-trash" onclick="del_row(' + options.rowId + ')" title="删除行" style="margin:0 2px;">删除</span></div>';
    }

    var mydata = [];
    for (var i = 0; i < 5; i++) {
      var obj = { id: i + 1 ,}
      mydata.push(obj);
    };


    for (var i = 0; i <= mydata.length; i++) {
      jQuery("#grid").jqGrid('addRowData', i + 1, mydata[i]);
    }

     // 选择仓库弹窗
    $(".grid-wrap").on("click", ".store_name_details", function (e) {
      var top = $(this).offset().top;
      var left = $(this).offset().left;
      $("#droplist_store").show();
      $("#droplist_store").css({ "top": (top + 5) + "px", "left": (left - 100) + "px" })
    })

   





  });





  // 表头 批量按钮 点击样式
  function batchBtn(id) {
    $("#snapshotTipsBox").addClass("pcnone");
    if (id == 1) {
      $("#storageBox2").addClass('pcnone');
      $("#storageBox3").addClass('pcnone');
    } else if (id == 2) {
      $("#storageBox1").addClass('pcnone');
      $("#storageBox3").addClass('pcnone');
    } else if (id == 3) {
      $("#storageBox1").addClass('pcnone');
      $("#storageBox2").addClass('pcnone');
    }

    var top = $("#batchStorage" + id).offset().top;
    var left = $("#batchStorage" + id).offset().left;
    if ($("#storageBox" + id).hasClass("pcnone")) {
      $("#storageBox" + id).removeClass('pcnone');//removeClass
      $("#storageBox" + id).css({ 'left': (left - 25) + 'px', 'top': (top + 30) + 'px' });
    } else {
      $("#storageBox" + id).addClass('pcnone');
    }
  }
  // 点击弹窗确定按钮事件
  function closeStorage(id) {
    $("#storageBox" + id).addClass('pcnone');
  }

  // 点击表头可用库存
  function snapshotTipsFun() {
    var top = $("#snapshotTipsBtn").offset().top;
    var left = $("#snapshotTipsBtn").offset().left;
    if ($("#snapshotTipsBox").hasClass("pcnone")) {
      $("#snapshotTipsBox").removeClass("pcnone");
      $("#snapshotTipsBox").css({ "top": (top + 30) + "px", "left": (left - 25) + "px" });
      $("#storageBox1").addClass('pcnone');
      $("#storageBox2").addClass('pcnone');
      $("#storageBox3").addClass('pcnone');
    } else {
      $("#snapshotTipsBox").addClass("pcnone");
    }

  }


  // 下拉选择
  function chooseSelect(id, value, text) {
    console.log(value, text)
    $("#storageInput" + id).val(text);
    storageList(id);
  }

  // 关闭下拉选择
  function storageList(id) {
    $("#storageList" + id).hide();
  }

  // 表头扫描枪录入的开关
  function smq() {

    if ($("#barCodeInsert").hasClass("close")) {
      $("#barCodeInsert").addClass('open');
      $("#barCodeInsert").removeClass('close');//removeClass

    } else {
      if ($("#barCodeInsert").hasClass("open")) {
        $("#barCodeInsert").addClass('close');
        $("#barCodeInsert").removeClass('open');//removeClass
      }
    }

  }


</script>
<script>


  // 采购费用
 //  function expenseInfoFun(url, obj) {
 //    var o = $(obj);
 //    layer.open({
 //      type: 2,
 //      title: "采购费用",
 //      shadeClose: true,
 //      shade: 0.3,
 //      maxmin: false, //开启最大化最小化按钮
 //      area: ['650px', '400px'],
 //      fixed: false, //不固定
 //      btn: ['确定', '取消'],
 //      //btn: ['btn1','btn2'],
 //      content: url,
 //      btn1: function (index, layero) {
 //        var body = layer.getChildFrame('body', index);
 //        // body.find('#grid').jqGrid('getGridParam', 'data').trigger("reloadGrid");

 //        // 刷新表格值
 //        body.find("#reloadTable").click();

 //        var gridData = body.find('#grid').jqGrid('getGridParam', 'data');
 //        let arraydata = gridData;
 //        gridData = JSON.stringify(gridData);
 //        localStorage.setItem("purchase_data", gridData)

 //        var zk_lv = 0;
 //        for (let index = 0; index < arraydata.length; index++) {
 //          const element = arraydata[index];
 //          zk_lv = parseFloat(zk_lv / 1 + element.jine / 1).toFixed(2);
 //        }
 //        $('#purchase_cost').val(zk_lv);
 //        layer.close(index);
 //        // var obj = body.find('#grid');
 //        // var gridData = getJQAllData(obj);
 //        // var supplierid = body.find('input[name="goodid"]:checked').val();

 //        // if (supplierid == '' || supplierid == null) {
 //        //   layer.msg("请选择供应商");
 //        //   return false;
 //        // } else {
 //        //   //获取商品信息
 //        //   $.get("/admin/basic/one_customer.html", { id: supplierid }, function (data, state) {
 //        //     if (data.status == 1) {
 //        //       $("#customer input").val(data.info.sn + " " + data.info.name);
 //        //       $('#supplierid').val(data.info.id);
 //        //       layer.close(index);
 //        //     } else {
 //        //       layer.msg("获取商品信息失败");
 //        //     }
 //        //   })
 //        // }
 //        // layer.close(index);
 //        return false;
 //      },
 //      btn2: function (index, layero) {
 //        layer.close(index);
 //        return false;
 //      }
 //    })
 //  }

 //  // 分摊采购费用
 //  function doExpense() {
 //    var purchase_cost = $('#purchase_cost').val();
 //    var data = getJQAllData($("#grid"));
 //    var total = 0;
 //    for (let index = 0; index < data.length; index++) {
 //      const element = data[index];
 //      total = total / 1 + element['total_price'] / 1;
 //    }
 //    for (let index = 0; index < data.length; index++) {
 //      const element = data[index];
 //      $("#grid").jqGrid("setCell", element['id'], 'purchase_cost', parseFloat(element['total_price'] / 1 / total * purchase_cost).toFixed(2));
 //    }
 //  }

</script>

<script type="text/javascript">
  var grid = $('#grid');

  $(".wrapper").on("click", "#savaAndAdd", function (e) {
    //先保存
    save_jqgrid(edit_row, edit_col, grid, function (res) {
      savedata(1);

    });
  })

  $(".wrapper").on("click", "#o_shenhe", function (e) {
    //先保存
    save_jqgrid(edit_row, edit_col, grid, function (res) {
      savedata(4);
      
    });
  })



  $(".wrapper").on("click", "#save", function (e) {
    save_jqgrid(edit_row, edit_col, grid, function (res) {
      $("#grid").jqGrid().trigger("reloadGrid");
      layer.msg("保存成功");
    });
  })
  //1.添加，2编辑，3复制，4，审核订单
  function savedata(type_btn) {

    var gooddata = $('#grid').jqGrid('getGridParam', 'data');
    var flag = 0;
    var hasuser = 0;
    var hasuser1 = 0;
    var indexArr = [];
    //console.log(gooddata);
    gooddata.forEach(function (self, index) {
      //console.log(self);   ""1
      if (self['good_id'] != null && self['good_id']!="") {
        // console.log("good");
        hasuser = hasuser + 1;
        if (self['store_id'] == null || self['store_id']=="") {
          flag = 1;
          indexArr.push(index);
        }else{
           hasuser1 = hasuser1 + 1;
        }
      }
    });
    if (hasuser == 0) {
      layer.msg("请选择商品");
      // 必填项（商品）
      $("#grid").editCell(1,3,true);
      return false;
    }

    if (flag == 1) {
      layer.msg("请选择仓库");
      // 必填项（仓库）
      $("#grid").editCell(indexArr[0]+1,6,true);
      return false;
    }

    var customerid = $("#customerid").val();//客户ID
    if (customerid == "") {
      layer.msg('请先选择供应商');
      return false;
    }

    var account_id = $("#account_id").val();//结算账户
    var accountdata = [];

    var purchase_data = JSON.parse(localStorage.getItem("purchase_data"));//采购数据

    if (account_id == -1) {
      var account_total_price = $("#account_total_price").val();
      if (payment != account_total_price) {
        layer.msg("多账户金额不等于本次收款金额");
        return false;
      }
      accountdata = JSON.parse(localStorage.getItem("more_account_data"));//多账户 
    }
    var movedata = gooddata;
    var dj_time = $("#dj_time").val();//单据日期
   // var jh_time = $("#jh_time").val();//交货日期
    var sn = $("#number").html();//单据号
    var mark = $("#note").val();//备注
    var type = $('input:radio[name="type"]:checked').val();//业务类别
    var yh_lv = $("#yh_lv").val();//优惠率
    var yh_e = $("#yh_e").val();//优惠额
    var yh_price = $("#yh_price").val();//优惠后价格
    var before_yh_price = $("#before_yh_price").val();//优惠前价格

    var payment = $("#payment").val();//本次收款
    var arrears = $("#arrears").val();//本次欠款
    var total_arrears = $("#total_arrears").val();//累计欠款
    var type = 1;//是否是退货

    if (type_btn == 1) {
      //新增
      var param = { before_yh_price: before_yh_price, user_id: customerid, sn: sn, mark: mark, movegood: movedata, dj_time: dj_time,  yh_lv: yh_lv, yh_e: yh_e, yh_price: yh_price, type: type,payment:payment,arrears:arrears ,total_arrears:total_arrears, account: account_id, accountdata:accountdata};
      var url = "save.html";
    } else if (type_btn == 4) {
      //直接审核
      var param = { o_shenhe: 1, before_yh_price: before_yh_price, user_id: customerid, sn: sn, mark: mark, movegood: movedata, dj_time: dj_time, yh_lv: yh_lv, yh_e: yh_e, yh_price: yh_price, type: type,payment:payment,arrears:arrears ,total_arrears:total_arrears, account: account_id, accountdata:accountdata, };
      var url = "save.html";

    }

    $.ajax({
      type: 'POST',
      url: url,
      data: param,
      dataType: "json",
      async: false,
      error: function (request) {
        layer.msg("发送请求失败！");
      },
      success: function (data) {
        if (data.status == 1) {
          if(type_btn==4){
            layer.msg("审核成功！");
            if(data.editId && data.editId != 0 ){
              setTimeout(function () {
                location.href="/scm/invre/edit.html?id="+data.editId;
              }, 2900);
            }
          }else{
            layer.alert(data.msg, function () {
              location.reload();
            });
          }
          
        } else {
          layer.msg(data.msg);
        }

      }
    });

  }


</script>
{include file="admin@public/footer" /}